package pyip.lib.javalearn;

import java.io.PrintStream;

/**
 * A thread-safe console printer tool.
 * This class delegate operations to System.out or System.err.
 * @author yepeng
 * @date 2015年4月28日
 */
public class Printer {
    private PrintStream innerPrintStream;
    public static final Printer out = new Printer(System.out);
    public static final Printer err = new Printer(System.err);

    private Printer(PrintStream innerOut) {
        this.innerPrintStream = innerOut;
    }

    public void println() {
        innerPrintStream.println();
    }

    /**
     * 不打印时间
     * @param msg
     */
    public void println(Object msg) {
        println(msg, 0, false);
    }

    /**
     * 打印时间
     * @param msg
     * @param level
     */
    public void println(Object msg, int level) {
        println(msg, level, true);
    }

    public void println(Object msg, int level, boolean withTimestamp) {
        if (msg == null || msg.toString().trim().equals("")) {
            innerPrintStream.println();
        } else {
            innerPrintStream.println(getIndent(level) + msg + (withTimestamp ? ", " + Timer.getSecondsString() : ""));
        }
    }

    private String getIndent(int level) {
        if (level <= 0) {
            return "";
        }

        String indent = "";
        for (int i = 0; i < level; i++) {
            indent += "\t";
        }
        return indent;
    }

}
